package com.zcy.auth.service.impl;

import com.zcy.auth.dto.LoginDTO;
import com.zcy.auth.service.ILoginService;
import com.zcy.auth.vo.LoginVO;
import com.zcy.basic.data.ContextData;
import com.zcy.pmp.domain.Employee;
import com.zcy.pmp.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author lucker
 * @date 2023/12/5 9:58
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        if (loginDTO == null || loginDTO.getUsername() == null || loginDTO.getPassword() == null || loginDTO.getUsername().isEmpty() || loginDTO.getPassword().isEmpty()) {
            throw new RuntimeException("用户名或密码不能为空");
        }
        Employee employee = employeeMapper.queryByUsername(loginDTO.getUsername());
        if (employee != null && employee.getPassword().equals(loginDTO.getPassword())) {
            Employee user = new Employee();
            user.setUsername(employee.getUsername())
                    .setAge(employee.getAge())
                    .setEmail(employee.getEmail())
                    .setHeadImage(employee.getHeadImage());
            String token = UUID.randomUUID().toString();
            ContextData.LOGIN_MAP.put(token, employee);

            return new LoginVO().setToken(token).setUser(user);
        } else {
            throw new RuntimeException("用户名或密码错误");
        }
    }
}
